package com.kbbywyclient.ui.activity;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.kbbywyclient.R;
import com.kbbywyclient.app.API;
import com.kbbywyclient.app.App;
import com.kbbywyclient.data.entity.Event;
import com.kbbywyclient.data.entity.MobileLoginOfRegist;
import com.kbbywyclient.data.entity.RegistUser;
import com.kbbywyclient.data.entity.User;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.LoginModule;
import com.kbbywyclient.presenter.LoginPresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.adapter.ViewPagerAdapter;
import com.kbbywyclient.ui.contarct.LoginContract;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.CheckFormat;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.util.ViewUtils;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomDialog;
import com.kbbywyclient.widget.CustomToolBar;
import com.kbbywyclient.widget.NoScrollViewPager;
import com.ogaclejapan.smarttablayout.SmartTabLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 登陆页面
 * Created by FHW
 * on 2017/3/23
 */

public class LoginActivity extends BaseActivity implements LoginContract.View {
    public static final String REQUEST_LOGIN_TYPE_I="type";

    @BindView(R.id.v_toolbar)
    CustomToolBar v_toolbar;
    @BindView(R.id.vp_viewpager)
    NoScrollViewPager vp_viewpager;
    @BindView(R.id.stb_viewpagertab)
    SmartTabLayout stb_viewpagertab;
    @BindView(R.id.tv_login)
    TextView tv_login;
    @BindView(R.id.cb_remember_pwd)
    CheckBox cb_remember_pwd;

    private ViewPagerAdapter pagerAdapter;
    private List viewContainter;
    private ArrayList<String> titles;

    private int mType = 0;
    //账号登录//////
    private EditText et_username;
    private EditText et_pwd;
    private String str_mobileOrEma = "";
    private String str_pwd = "";
    private boolean isUserFillIn = false;

    //手机登录//////
    private EditText et_phone;
    private EditText et_v_code;
    private TextView tv_get_Code;
    private String str_mobile = "";
    private String str_code = "";
    private boolean isMobileFillIn = false;
    //验证码
    private final int START_CODE = 1;
    private final int COUNT_CODE = 2;
    private final int END_CODE = 3;
    private boolean isGetCode = false;
    private final int GET_CODE_TIME = 90;
    private int codeTime = 0;

    private String SalesID = "";

    @Inject
    LoginPresenter loginPresenter;

    private CustomDialog dialog;
    private boolean isRemember = true;
    private int refreshType = -1;

    @Override
    public int provideContentViewId() {
        return R.layout.activity_login;
    }

    @OnClick({R.id.tv_login, R.id.tv_forget_pwd})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_login:
                switch (mType) {
                    case 0://账号登录
                        if (vertifyUser()) {
//                            loginPresenter.getUserLogin(str_mobileOrEma, str_pwd, StringUtil.getDeviceId(this), API.APPType);
                            loginPresenter.getUserLogin(str_mobileOrEma, str_pwd, App.mDeviceToken, API.APPType);
                        }
                        break;
                    case 1://手机登录
                        if (isGetCode) {
                            if (!str_code.isEmpty()) {
//                                loginPresenter.getMobileCodeLoginOfRegist(SalesID, str_mobile, str_code
//                                        , StringUtil.getDeviceId(this), API.APPType, "");
                                loginPresenter.getMobileCodeLoginOfRegist(SalesID, str_mobile, str_code
                                        , App.mDeviceToken, API.APPType, "");
                            } else {
                                ToastUtil.showShort("请输入验证码");
                            }
                        } else {
                            ToastUtil.showShort("请获取验证码");
                        }
                        break;
                }
                break;
            case R.id.tv_forget_pwd:
                ActivitySkipUtil.skipAnotherActivity(this, RetrievePwdOneActivity.class);
                break;
        }
    }

    private boolean vertifyUser() {
        if (str_mobileOrEma.isEmpty()) {
            ToastUtil.showShort("请输入手机号/邮箱");
            return false;
        }
        if (!(CheckFormat.isMobile(str_mobileOrEma) || CheckFormat.isEmail(str_mobileOrEma))) {
            ToastUtil.showShort("请输入正确的手机号/邮箱");
            return false;
        }
        if (str_pwd.isEmpty()) {
            ToastUtil.showShort("请输入密码");
            return false;
        }
        if (!CheckFormat.isPwd(str_pwd)) {
            ToastUtil.showShort("密码须为6-15位");
            return false;
        }
        return true;
    }


//    public PagerInfo[] getPagers() {
//        String[] titles = new String[]{"账 号 登 录", "手机验证登录"};
//        PagerInfo[] infoList = new PagerInfo[2];
//        infoList[0] = new PagerInfo(titles[0], UserLoginFragment.class, null);
//        infoList[1] = new PagerInfo(titles[1], MobileLoginFragment.class, null);
//        return infoList;
//    }


    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("登录页");
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        ImmersionBar.with(this).keyboardEnable(true).init();

        refreshType = getIntent().getIntExtra("type", -1);

        v_toolbar.setLeftViewOnClickLinster(v -> finish());
        v_toolbar.setRightViewOnClickLinster(v -> ActivitySkipUtil.skipAnotherActivity(this, RegisterActivity.class));

//        adapter = new BaseFViewpagerAdapter(getSupportFragmentManager(), getPagers(), this);
//        vp_viewpager.setAdapter(adapter);
//        vp_viewpager.setOffscreenPageLimit(2);

        setViewPager();

        stb_viewpagertab.setViewPager(vp_viewpager);

        stb_viewpagertab.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mType = position;
                switch (position) {
                    case 0://账号登录
                        cb_remember_pwd.setVisibility(View.VISIBLE);
                        if (isUserFillIn) {
                            tv_login.setBackgroundResource(R.drawable.textview_bg_14c095);
                        } else {
                            tv_login.setBackgroundResource(R.drawable.textview_bg_20ffffff);
                        }
                        break;
                    case 1://手机登录
                        cb_remember_pwd.setVisibility(View.INVISIBLE);
                        if (isMobileFillIn) {
                            tv_login.setBackgroundResource(R.drawable.textview_bg_14c095);
                        } else {
                            tv_login.setBackgroundResource(R.drawable.textview_bg_20ffffff);
                        }
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        cb_remember_pwd.setOnCheckedChangeListener((buttonView, isChecked) -> {
            isRemember = isChecked;
        });

    }

    /**
     * 设置viewpager页面
     */
    private void setViewPager() {
        viewContainter = new ArrayList<>();
        titles = new ArrayList<>();
        titles.add("账 号 登 录");
        titles.add("手机验证登录");

        //账号登录
        View view = LayoutInflater.from(this).inflate(R.layout.fragment_user_login, null);

        et_username = (EditText) view.findViewById(R.id.et_username);
        et_pwd = (EditText) view.findViewById(R.id.et_pwd);

        str_mobileOrEma = PreUtils.getUserAccount(this);
        et_username.setText(str_mobileOrEma);
        if (PreUtils.isRemember(this)) {
            str_pwd = PreUtils.getUserPwd(this);
            et_pwd.setText(str_pwd);
            tv_login.setBackgroundResource(R.drawable.textview_bg_14c095);
            isUserFillIn = true;
        }

//        et_username.setInputType(InputType.TYPE_CLASS_NUMBER);
//        String digists = "0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@._";
//        et_username.setKeyListener(DigitsKeyListener.getInstance(digists));

        et_username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                str_mobileOrEma = s.toString();
                isUserLoginFillIn();
            }
        });
        et_pwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                str_pwd = s.toString();
                isUserLoginFillIn();
            }
        });

        // viewpager开始添加view
        viewContainter.add(view);

        //手机验证登录登录
        View view1 = LayoutInflater.from(this).inflate(R.layout.fragment_mobile_login, null);

        et_phone = (EditText) view1.findViewById(R.id.et_phone);
        et_v_code = (EditText) view1.findViewById(R.id.et_v_code);
        tv_get_Code = (TextView) view1.findViewById(R.id.tv_get_Code);

        str_mobile = PreUtils.getUserAccount(this);
        et_phone.setText(str_mobile);

        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                str_mobile = s.toString();
                if (CheckFormat.isMobile(str_mobile)) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(et_phone.getWindowToken(), 0); //强制隐藏键盘
                    }
                }
            }
        });
        et_v_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                str_code = s.toString();
                if (CheckFormat.isCode(str_code)) {
                    if (isGetCode) {
                        isMobileFillIn = true;
                        tv_login.setBackgroundResource(R.drawable.textview_bg_14c095);
                    }
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(et_v_code.getWindowToken(), 0); //强制隐藏键盘
                    }
                } else {
                    tv_login.setBackgroundResource(R.drawable.textview_bg_20ffffff);
                    isMobileFillIn = false;
                }
            }
        });

        tv_get_Code.setOnClickListener(v -> getCode());

        // viewpager开始添加view
        viewContainter.add(view1);

        // 设置适配器
        pagerAdapter = new ViewPagerAdapter(viewContainter, titles);
        vp_viewpager.setAdapter(pagerAdapter);

    }

    /**
     * 获取验证码
     */
    private void getCode() {
        if (str_mobile.isEmpty()) {
            ToastUtil.showShort("请输入手机号码");
        } else if (!CheckFormat.isMobile(str_mobile)) {
            ToastUtil.showShort("请输入正确的手机号码");
        } else {
            if (!isGetCode) {
//                loginPresenter.sendOfCheckMobileCode(str_mobile, "1");
                loginPresenter.checkMobile(str_mobile);
            }
        }
    }

    @Override
    public void initData() {

    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getLoginComponent(new LoginModule(this)).inject(this);
    }

    /**
     * 判断账号填写完成的操作
     */
    private void isUserLoginFillIn() {
        if ((CheckFormat.isMobile(str_mobileOrEma) || CheckFormat.isEmail(str_mobileOrEma)) && CheckFormat.isPwd(str_pwd)) {
            tv_login.setBackgroundResource(R.drawable.textview_bg_14c095);
            if (CheckFormat.isPwdFinish(str_pwd)) {
                isUserFillIn = true;
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(et_username.getWindowToken(), 0); //强制隐藏键盘
                }
            }
        } else {
            tv_login.setBackgroundResource(R.drawable.textview_bg_20ffffff);
            isUserFillIn = false;
        }
    }

    /**
     * 手机登录 回调
     *
     * @param mobileLogin
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event.MobileLogin mobileLogin) {
        vp_viewpager.setCurrentItem(1);
        str_mobile = mobileLogin.getStr_mobile();
        et_phone.setText(str_mobile);
        if (!isGetCode) {
//            loginPresenter.sendOfCheckMobileCode(str_mobile, "");
            loginPresenter.sendMobileCodeNews(str_mobile);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case START_CODE:
                    codeTime = GET_CODE_TIME;
                    isGetCode = true;
                    handler.sendEmptyMessage(COUNT_CODE);
                    break;
                case COUNT_CODE:
                    if (codeTime <= 0) {
                        handler.sendEmptyMessage(END_CODE);
                    } else {
                        tv_get_Code.setTextColor(getResources().getColor(R.color.color_14C095));
                        ViewUtils.setText(tv_get_Code, codeTime-- + "s");
                        handler.sendEmptyMessageDelayed(COUNT_CODE, 1000);
                    }
                    break;
                case END_CODE:
                    isGetCode = false;
                    tv_get_Code.setTextColor(getResources().getColor(R.color.color_ffffff));
                    ViewUtils.setText(tv_get_Code, R.string.text_get_code);
                    break;
            }
            return false;
        }
    });


    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    @Override
    public void loadSucUserLogin(User user) {
        // 保存用户信息
        saveUserInfo(user);
        PreUtils.setRemember(this, isRemember);
        PreUtils.setUserAccount(this, str_mobileOrEma);
        PreUtils.setUserPwd(this, str_pwd);
        setResult(RESULT_OK, getIntent());
        EventBus.getDefault().post(new Event.RefreshIndex(refreshType));
        EventBus.getDefault().post(new Event.AccountSignIn());
        finish();
    }

    private void saveUserInfo(User user) {
        PreUtils.saveUser(LoginActivity.this, user);
        PreUtils.setLogin(LoginActivity.this, true);
    }

    @Override
    public void loadFaiUserLogin(String errorMsg) {

    }

    @Override
    public void loadSucCheck(RegistUser registUser) {
        switch (registUser.getNewUser()) {
            case 0://已注册
//                loginPresenter.sendOfCheckMobileCode(str_mobile, "");
                loginPresenter.sendMobileCodeNews(str_mobile);
                break;
            case 1://未注册
                dialog = new CustomDialog(this, R.style.Customdialog, "该手机号未注册", "验证手机号可直接注册！", new CustomDialog.ButtonListener() {
                    @Override
                    public void left() {
                        ActivitySkipUtil.skipAnotherActivity(LoginActivity.this, RegisterActivity.class);
                        dialog.dismiss();
                        EventBus.getDefault().postSticky(new Event.MobileRegist(str_mobile));
                    }

                    @Override
                    public void right() {
                        dialog.dismiss();
                    }
                }, getString(R.string.text_get_code), getString(R.string.cancel));
                dialog.show();
                break;
        }
    }

    @Override
    public void loadFaiCheck(String errorMsg) {

    }

    @Override
    public void loadSucCode(RegistUser registUser) {
        SalesID = registUser.getSalesID() + "";
        handler.sendEmptyMessage(START_CODE);
    }

    @Override
    public void loadFaiCode(String errorMsg) {

    }

    @Override
    public void loadSucLoginOfRegist(MobileLoginOfRegist mobileLoginOfRegist) {
        int city = -1;
        if (mobileLoginOfRegist.getCity() instanceof Integer) {
            city = (int) mobileLoginOfRegist.getCity();
        }
        User user = new User(
                mobileLoginOfRegist.getSalesID(),
                city,
                mobileLoginOfRegist.getCityName(),
                mobileLoginOfRegist.getGoToType(),
                mobileLoginOfRegist.getIsOpenRpacket(),
                mobileLoginOfRegist.getRole());
        // 保存用户信息
        saveUserInfo(user);
        PreUtils.setUserAccount(this, str_mobile);
        setResult(RESULT_OK, getIntent());
        EventBus.getDefault().post(new Event.RefreshIndex(refreshType));
        finish();
    }

    @Override
    public void loadFaiLoginOfRegist(String errorMsg) {

    }
}
